﻿using mozhi.smarterp.BasicData.DataLinkages.Events;
using Mozhi.Abp.Module.DataLinkage;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
using Volo.Abp.EventBus.Distributed;
using Volo.Abp.Guids;
using Volo.Abp.MultiTenancy;

namespace mozhi.smarterp.BasicData.DataLinkages.EventHandlers
{
    public class DataLinkageCreateEventHandler : IDistributedEventHandler<BasicDataLinkageCreateEvent>,
          ITransientDependency
    {
        private IDataLinkageRepository _repository;
        private IGuidGenerator _guidGenerator;
        private ICurrentTenant _currentTenant;

        public DataLinkageCreateEventHandler(IDataLinkageRepository repository , IGuidGenerator guidGenerator , ICurrentTenant currentTenant)
        {
            _repository = repository;
            _guidGenerator = guidGenerator;
            _currentTenant = currentTenant;
        }

        public async Task HandleEventAsync(BasicDataLinkageCreateEvent eventData)
        {
            using (_currentTenant.Change(eventData.TenantId))
            {
                var dataLinkage = (await _repository.GetListAsync(null, eventData.ProviderId, eventData.ConsumerId)).FirstOrDefault();

                //存在就不处理了，实现等幂处理
                if (dataLinkage != null)
                    return;

                dataLinkage = new DataLinkage(_guidGenerator.Create(), eventData.ProviderId, eventData.ProviderContent,
                       eventData.ConsumerId, eventData.ConsumerContent, eventData.ProviderType, eventData.ConsumerType);

                await _repository.InsertAsync(dataLinkage);
            }
        }
    }
}
